package cn.xuqiudong.demo.mvc.redis.redisson;

import org.apache.commons.lang3.time.DateFormatUtils;
import org.redisson.api.RAtomicLong;
import org.redisson.api.RLock;
import org.redisson.api.RedissonClient;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import javax.annotation.PostConstruct;
import java.time.Instant;
import java.time.temporal.ChronoUnit;
import java.util.List;
import java.util.concurrent.CopyOnWriteArrayList;
import java.util.concurrent.TimeUnit;

/**
 * 说明: 测试redisson
 *
 * @author Vic.xu
 * @since 2023/5/9/0009 13:55
 */
@Service
public class RedissonLockService {

    @Autowired
    private RedissonClient redissonClient;

    public long dailySequence(String lockName) {
        RLock lock = redissonClient.getLock(lockName);

        try {
            boolean locked = lock.tryLock(5, 10, TimeUnit.SECONDS);
            if (locked) {
                String today = DateFormatUtils.format(System.currentTimeMillis(), "yyyyMMdd");
                String key = "lock:" + lockName + ":" + today;
                RAtomicLong atomicLong = redissonClient.getAtomicLong(key);
                long seq = atomicLong.incrementAndGet();
                if (seq == 1) {
                    Instant tomorrow = Instant.now().plus(1, ChronoUnit.DAYS);
                    atomicLong.expire(tomorrow);
                }
                return seq;
            } else {
                throw new RuntimeException("get lock[" + lockName + "] failure!");
            }

        } catch (InterruptedException e) {
            throw new RuntimeException(e);
        }

    }

    private static List<Long> copyList = new CopyOnWriteArrayList<>();

    @PostConstruct
    private void init() {
        System.out.println("into RedissonLockService#init ");

        String locKName = "test";
        for (int i = 0; i < 100; i++) {
            long l = dailySequence(locKName);
            copyList.add(l);
        }
        print();

    }

    private static void print() {
        int size = copyList.size();
        int row = 30;
        for (int i = 0; i < size; i++) {
            if (i > 0 && i % row == 0) {
                System.out.println();
            }
            Long n = copyList.get(i);
            System.out.print(n + ", ");


        }
    }
}
